<template>
  <div class="order-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
          <div>
            <el-button @click="refreshData">刷新</el-button>
            <el-button type="primary" @click="handleAddOrder">新增订单</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="制作中" value="preparing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 订单列表 -->
      <el-table :data="orderList" stripe style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="tableId" label="桌号" width="80" />
        <el-table-column prop="customerInfo" label="客户信息" width="120" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看详情</el-button>
            <el-button size="small" @click="handleEditOrder(scope.row)">编辑</el-button>
            <el-button 
              v-if="scope.row.status === 'pending'" 
              size="small" 
              type="primary" 
              @click="handleProcessOrder(scope.row)"
            >
              处理订单
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteOrder(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="桌号">{{ currentOrder.tableId }}</el-descriptions-item>
        <el-descriptions-item label="客户信息">{{ currentOrder.customerInfo }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusTagType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="确认时间">{{ currentOrder.confirmTime }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ currentOrder.payTime }}</el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 新增/编辑订单对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editForm.id ? '编辑订单' : '新增订单'" width="600px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="editForm.orderNo" />
        </el-form-item>
        <el-form-item label="桌号" prop="tableId">
          <el-select v-model.number="editForm.tableId" placeholder="请选择桌号">
            <el-option
              v-for="item in tableOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户信息" prop="customerInfo">
          <el-input v-model="editForm.customerInfo" />
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input v-model.number="editForm.totalAmount" type="number" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="pending" />
            <el-option label="制作中" value="preparing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="editForm.paymentMethod" placeholder="请选择支付方式" clearable>
            <el-option label="微信" value="微信" />
            <el-option label="支付宝" value="支付宝" />
            <el-option label="银行卡" value="银行卡" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveOrder">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElCard, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, 
         ElTable, ElTableColumn, ElTag, ElPagination, ElDialog, ElDescriptions, 
         ElDescriptionsItem, ElMessage, ElMessageBox } from 'element-plus'
import { getOrderList, getOrderById, createOrder, updateOrder, processOrder, deleteOrder } from '@/api/order'

// 桌号选项
const tableOptions = ref([
  { value: 1, label: 't001(4人桌)' },
  { value: 2, label: 't002(6人桌)' },
  { value: 3, label: 't003(2人桌)' }
])

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: ''
})

// 订单列表数据
const orderList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref({})

// 编辑对话框
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  orderNo: '',
  tableId: null,
  customerInfo: '',
  totalAmount: null,
  status: 'pending',
  paymentMethod: ''
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    pending: 'warning',
    preparing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    preparing: '制作中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || ''
}

// 查看详情
const viewDetail = async (order) => {
  try {
    const response = await getOrderById(order.id)
    if (response.code === 200) {
      currentOrder.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取订单详情失败')
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败: ' + error.message)
  }
}

// 新增订单
const handleAddOrder = () => {
  // 重置表单
  Object.assign(editForm, {
    id: null,
    orderNo: '',
    tableId: 1, // 设置默认桌号为1，确保外键约束有效
    customerInfo: '',
    totalAmount: null,
    status: 'pending',
    paymentMethod: ''
  })
  editDialogVisible.value = true
}

// 编辑订单
const handleEditOrder = (order) => {
  Object.assign(editForm, { ...order, tableId: order.tableId || 1 }) // 确保tableId有有效值
  editDialogVisible.value = true
}

// 保存订单（新增或编辑）
const saveOrder = async () => {
  try {
    let response
    if (editForm.id) {
      // 编辑订单
      const { id, ...updateData } = editForm
      response = await updateOrder(id, updateData)
    } else {
      // 新增订单
      response = await createOrder(editForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(editForm.id ? '订单更新成功' : '订单创建成功')
      editDialogVisible.value = false
      fetchOrderList() // 刷新列表
    } else {
      ElMessage.error(response.msg || (editForm.id ? '订单更新失败' : '订单创建失败'))
    }
  } catch (error) {
    ElMessage.error(editForm.id ? '订单更新失败: ' + error.message : '订单创建失败: ' + error.message)
  }
}

// 处理订单
const handleProcessOrder = (order) => {
  ElMessageBox.confirm(`确定要处理订单${order.orderNo}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API更新订单状态
      const response = await processOrder(order.id, { status: 'preparing' })
      if (response.code === 200) {
        // 更新订单状态
        const index = orderList.value.findIndex(item => item.id === order.id)
        if (index !== -1) {
          orderList.value[index].status = 'preparing'
        }
        ElMessage.success('订单处理成功')
      } else {
        ElMessage.error(response.msg || '订单处理失败')
      }
    } catch (error) {
      ElMessage.error('订单处理失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 删除订单
const handleDeleteOrder = (order) => {
  ElMessageBox.confirm(`确定要删除订单${order.orderNo}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteOrder(order.id)
      if (response.code === 200) {
        ElMessage.success('订单删除成功')
        fetchOrderList() // 刷新列表
      } else {
        ElMessage.error(response.msg || '订单删除失败')
      }
    } catch (error) {
      ElMessage.error('订单删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchOrderList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = ''
  searchForm.status = ''
  fetchOrderList()
}

// 刷新数据
const refreshData = () => {
  fetchOrderList()
}

// 分页相关处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchOrderList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchOrderList()
}

// 获取订单列表
const fetchOrderList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      orderNo: searchForm.orderNo,
      status: searchForm.status
    }
    
    const response = await getOrderList(params)
    if (response.code === 200) {
      orderList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.msg || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败: ' + error.message)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>